package cn.edu.lingnan.fruitshop.service.impl;

import cn.edu.lingnan.fruitshop.common.AlipayConfig;
import cn.edu.lingnan.fruitshop.mapper.*;
import cn.edu.lingnan.fruitshop.pojo.*;
import cn.edu.lingnan.fruitshop.service.OrdertableService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张小凡
 * @since 2022-01-04
 */
@Service
public class OrdertableServiceImpl extends ServiceImpl<OrdertableMapper, Ordertable> implements OrdertableService {
    @Resource
    private OrdertableMapper ordertableMapper;
    @Autowired(required = false)
    private OrderdetailMapper orderdetailMapper;
    @Resource
    private GoodstableMapper goodstableMapper;
    @Autowired(required = false)
    private AddressMapper addressMapper;
    @Autowired(required = false)
    private CarttableMapper carttableMapper;

    /**
     * 跳转用户订单界面
     * @param model
     * @param session
     * @return
     */
    @Override
    public String toUserCenterOrder(Model model, HttpSession session,Integer currentPage, Integer pageSize) {
//        判断跳转页数是否小于1
        if(currentPage==null||currentPage<1){
            currentPage=1;
        }
//        设置分页条件，以订单分页
        PageHelper.startPage(currentPage,pageSize);
//        获取用户信息
        User user = (User)session.getAttribute("user");
//        检索该用户订单信息
        QueryWrapper<Ordertable> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getUserId()).orderByDesc("order_date");
        List<Ordertable> list = ordertableMapper.selectList(queryWrapper);
//        分页处理
        PageInfo<Ordertable> pageInfo = new PageInfo<>(list);
        if(currentPage>pageInfo.getPages()&&pageInfo.getPages()!=0){
            return toUserCenterOrder(model,session,pageInfo.getPages(),pageSize);
        }
//        按照分页条件返回数据
        List<Ordertable> ordertables = pageInfo.getList();
        model.addAttribute("ordertables",ordertables);
//        将订单详情绑定到我的订单界面
        QueryWrapper<Orderdetail> queryWrapper1 = new QueryWrapper<>();
        List<Orderdetail> orderdetails = orderdetailMapper.selectList(queryWrapper1);
        model.addAttribute("orderdetails",orderdetails);
//        将商品列表绑定到我的订单界面
        QueryWrapper<Goodstable> queryWrapper2 = new QueryWrapper<>();
        List<Goodstable> goodstables = goodstableMapper.selectList(queryWrapper2);
        model.addAttribute("goodstables",goodstables);
        return "user/user_center_order";
    }


    //创建订单
    @Override
    public String creatOrder(Model model,Integer orderId,Integer addressId,HttpSession session) {
        Ordertable ordertable1 = ordertableMapper.selectById(orderId);
        QueryWrapper<Ordertable> wrapper = new QueryWrapper<>();
        wrapper.eq("id",orderId);
        Ordertable ordertable = new Ordertable().setOrderDate(new Date())
                .setStatus(2).setAddressId(addressId);
        ordertableMapper.update(ordertable,wrapper);
        Object carStatus = session.getAttribute("carStatus");
        QueryWrapper<Orderdetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ordedetail_id",orderId);
        //更新商品数量
        List<Orderdetail> list = orderdetailMapper.selectList(queryWrapper);
        for (Orderdetail orderdetail : list) {
            Goodstable goodstable = goodstableMapper.selectById(orderdetail.getGoodId());
            goodstable.setStore(goodstable.getStore()-orderdetail.getNum());
            int i = goodstableMapper.updateById(goodstable);
        }
        if(carStatus != null)
        {
            QueryWrapper<Orderdetail> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("ordedetail_id",orderId);
            List<Orderdetail> orderdetails = orderdetailMapper.selectList(wrapper1);
            User user = (User)session.getAttribute("user");
            for (Orderdetail orderdetail : orderdetails) {
                QueryWrapper<Carttable> carttableQueryWrapper = new QueryWrapper<>();
                carttableQueryWrapper.eq("good_id",orderdetail.getGoodId());
                carttableQueryWrapper.eq("user_id",user.getUserId());
                carttableMapper.delete(carttableQueryWrapper);
            }

        }
        model.addAttribute("orderId",orderId);
        model.addAttribute("price1",ordertable1.getPrice());
//        这个ok.html页面很丑，暂时未找到合适的模板
        return "user/ok";
    }

//    支付
    @Override
    public String pay(Model model, Integer orderId, Integer addressId, HttpSession session) throws AlipayApiException {
        Ordertable ordertable = ordertableMapper.selectById(orderId);
        QueryWrapper<Orderdetail> wrapper = new QueryWrapper<>();
        wrapper.eq("ordedetail_id",orderId);
        List<Orderdetail> list = orderdetailMapper.selectList(wrapper);
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
                AlipayConfig.gatewayUrl,
                AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json",
                AlipayConfig.charset,
                AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //这里设置支付后跳转的地址
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        // 订单编号
        String out_trade_no = UUID.randomUUID().toString();

        //付款金额，必填
//        String total_amount = String.valueOf(bill.getTicketnum()*bill.getPrice());
        String total_amount = ordertable.getPrice()+"";

        //订单名称，必填
//        String subject ="用户"+user.getAccount()+"影票订单";
        String subject ="";
        for (Orderdetail orderdetail : list) {
            Goodstable goodstable = goodstableMapper.selectById(orderdetail.getGoodId());
            subject = subject + goodstable.getName()+",";
        }
        //商品描述，可空
//        String body = "用户订购商品个数：" + bill.getTicketnum();
        String body = null;
        // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
        String timeout_express = "5m";

//        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
//                + "\"total_amount\":\""+ total_amount +"\","
//                + "\"subject\":\""+ subject +"\","
//                + "\"body\":\""+ body +"\","
//                + "\"timeout_express\":\""+ timeout_express +"\","
//                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                +"\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String form = alipayClient.pageExecute(alipayRequest).getBody();
//        System.out.println(form);
        User  user = (User) session.getAttribute("user");
//        //更改订单状态 TODO 清空购物车
        creatOrder(model, orderId, addressId, session);

        return form;
    }

    /**
     * 根据订单id把 订单详情和订单 删除掉
     * @param id
     * @return
     */
    @Override
    public String deleteOrder(Model model,HttpSession session,Integer id,Integer currentPage) {
//        根据订单id把相关的订单详情删除掉
        HashMap<String,Object> map = new HashMap<>();
        map.put("ordedetail_id",id);
        orderdetailMapper.deleteByMap(map);
//        将订单本身删除
        ordertableMapper.deleteById(id);
//        return "redirect:/toUserCenterOrder";
        return toUserCenterOrder(model,session,currentPage,4);
    }

}
